#include <grpc/support/log.h>
#include "catch.hpp"
#include "action.hpp"

namespace etcdv3 {

ActionParameters::ActionParameters() {
    withPrefix = false;
    revision = 0;
    old_revision = 0;
    lease_id = 0;
    ttl = 0;
    kv_stub = nullptr;
    watch_stub = nullptr;
    lease_stub = nullptr;
    deadline = 0;
    async = false;
}

gpr_timespec ActionParameters::gainDeadline() {
    if (deadline <= 0) {
        return gpr_timespec{ 0, DefDeadLine, GPR_TIMESPAN };
    } else if (deadline >= (int64_t)TimeSecItv) {
        return gpr_timespec{ deadline / (int64_t)TimeSecItv, (int32_t)(deadline % (int64_t)TimeSecItv), GPR_TIMESPAN };
    } else {
        return gpr_timespec{ 0, (int32_t)deadline, GPR_TIMESPAN };
    }
}

Action::Action(const ActionParameters& params) {
    parameters = params;
}

void Action::waitForResponse() {
    void* got_tag;
    bool ok = false;

    if (parameters.async == false) {
        cq_.Next(&got_tag, &ok);
    } else {
        cq_.AsyncNext(&got_tag, &ok, parameters.gainDeadline());
    }
}

}
